<!-- 正文开始 -->
<style>
    .open-details-box::-webkit-scrollbar {
        display: none;
    }
    .x-red {
        color: red;
    }

    .lay-dialog-title {
        padding: 0 20px;
        position: relative;
        z-index: 99;
        border-bottom: 1px solid #e5e5e5;
        line-height: 39px;
        height: 39px;
        overflow: hidden;
        color: #666;
    }

    .lay-dialog-title label {
        color: #999
    }

    .w-100 {
        width: 100px !important;
    }

    .layui-table-cell{
        height: auto;
        max-height: 80px;
    }
    .layui-table-cell img {
        max-height: 80px;
    }

    .layui-form.model-form {
        padding: 0;
    }
    .cp{
        cursor: pointer;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <form class="layui-form">
                <div class="layui-form lay-header">
                    <div class="toolbar">
                        <div class="layui-form-item lay-query-content">
                            <div class="lay-query-box">
                                <div class="query-lt">
                                    <div class="layui-inline">
                                        <label class="layui-form-label">订单编号：</label>
                                        <div class="layui-input-inline">
                                            <input name="code" class="layui-input" type="text" placeholder="请输入订单编号" />
                                        </div>
                                    </div>
                                </div>
                                <div class="query-rt">
                                    <div class="layui-inline">
                                        <button type="button" class="layui-btn icon-btn color-green"
                                                lay-filter="formSubSearchLog" lay-submit type="button" layui-form-keyDownSearch="true">查询
                                        </button>
                                        <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit
                                                type="button">
                                            重置
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="lay-btn-rows">
                        <div class="lay-btn-box">
                            <div class="lay-btn-lt">
                                <button id="orderBtnAdd" class="layui-btn icon-btn" type="button">添加</button>
                            </div>
                            <div class="lay-btn-rt">
                            </div>
                        </div>
                    </div>
                </div>
            </form>
            <!-- 表格 -->
            <table class="layui-table" id="orderTable" lay-filter="orderTable"></table>
        </div>
    </div>
</div>

<style>
    form[lay-filter="orderForm"] label {
        width: 85px;
        padding: 9px 10px 9px 0;
    }

    div[lay-id="orderFormTable"] {
        overflow: auto;
    }

    .open-details-box::-webkit-scrollbar {
        width: 0 !important
    }

    form[lay-filter="orderForm"] .layui-table, .layui-table-view {
        margin: 2px 0px;
    }


    div[lay-id="productsInStockFormTable"] .layui-table-cell img,
    div[lay-id="orderFormTable"] .layui-table-cell img {
        max-height: 80px;
    }

    div[lay-id="orderFormTable"] .layui-table-box,
    div[lay-id="orderFormTable"] .layui-table-body,
    div[lay-id="orderFormTable"] .layui-table-cell,
    div[lay-id="orderDetailsTableList"] .layui-table-box,
    div[lay-id="orderDetailsTableList"] .layui-table-body,
    div[lay-id="orderDetailsTableList"] .layui-table-cell {
        overflow: visible;
        padding: 0 1px;
    }

    div[lay-id="productsInStockFormTable"] .layui-table-cell,
    div[lay-id="orderFormTable"] .layui-table-cell,
    div[lay-id="orderDetailsTableList"] .layui-table-cell {
        height: 80px;
        word-break: break-word;
        white-space: pre-line;
        padding: 0 5px;
    }


</style>

<!-- 表格操作列 -->
<script type="text/html" id="orderTableBar">
    {{# if(d.status=='pending'){  }}
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
   <!-- <a class="layui-btn layui-btn-xs" lay-event="confirm">审核</a>-->
    {{# }else{ }}
    <a class="layui-btn layui-btn-xs" lay-event="details">详情</a>
    {{# } }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="confirm">确认收货</a>
    <!--{{# if(d.status=='accept' && d.distributionStatus != 'complete'){  }}
    <a class="layui-btn layui-btn-xs" lay-event="audit">受理配货</a>
    {{# } }} -->
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="orderForm">
    <form lay-filter="orderForm" class="layui-form model-form"
          style="padding: 5px 30px 0 30px;height: calc(100% - 5px);overflow: hidden;">
        <div class="open-details-box"
             style="height: calc(100% - 100px); padding-top: 20px;overflow: auto;margin-bottom: 20px">
            <input name="id" type="hidden"/>
            <div class="layui-form-item">
                <label class="layui-form-label">销售方式</label>
                <div class="layui-input-inline">
                    <select name="mode"  lay-verify="required">
                        <option value="">请选择销售方式</option>
                        <option value="sell" >销售</option>
                        <option value="dist">铺货</option>
                        <option value="lease">租赁</option>
                        <!--<option value="give">赠送</option>-->
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">订单类型</label>
                <div class="layui-input-inline">
                    <select name="type" lay-filter="type" disabled>
                        <option value="cabinet">智能柜</option>
                    </select>
                </div>
            </div>
            <input name="customerCode" type="hidden"/>
            <div class="layui-form-item">
                <label class="layui-form-label">联系人</label>
                <div class="layui-input-inline">
                    <input name="contactsName" placeholder="请输入联系人" class="layui-input cp" lay-verify="required" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">电话</label>
                <div class="layui-input-inline">
                    <input name="phone" class="layui-input" type="text" placeholder="联系人电话" lay-verify="required" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">收货地址</label>
                <div class="layui-input-inline">
                    <input name="address" class="layui-input" type="text" placeholder="收货地址"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">订单备注</label>
                <div class="layui-input-inline">
                    <input name="remark" class="layui-input" type="text" placeholder="订单备注"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">订单总金额</label>
                <div class="layui-input-inline">
                    <input name="amount" class="layui-input" type="text" placeholder="订单总金额" readonly/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">到货时间</label>
                <div class="layui-input-inline">
                    <input name="arrivalTime" id="arrivalTime" class="layui-input" type="text" placeholder="到货时间"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">采购员</label>
                <div class="layui-input-inline">
                    <select name="operatorName" lay-verify="required" lay-search
                            lay-filter='operatorName'></select>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="open-details-title" style="margin-top: 20px">订单物料</div>
                <table class="layui-table" id="orderFormTable" lay-filter="orderFormTable"></table>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="orderFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- 客户弹窗 -->
<script type="text/html" id="customerList">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <form class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">客户名称：</label>
                                    <div class="layui-input-inline">
                                        <input name="customerName" class="layui-input" type="text" placeholder="请输入客户名称"/>
                                    </div>
                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn" lay-filter="customerListSubSearchLog" lay-submit>查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="customerListSearchReset" lay-submit>重置</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <a id="confirmChoose" class="layui-btn icon-btn">确认选择</a>
                        </div>
                    </div>
                </div>
            </form>
            <table class="layui-table" id="customerListTable" lay-filter="customerListTable"></table>
        </div>
    </div>
</script>

<!-- 客户联系人弹窗 -->
<script type="text/html" id="customerContactsList">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <form class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">客户名称：</label>
                                    <div class="layui-input-inline">
                                        <input name="name" class="layui-input" type="text" placeholder="请输入客户名称"/>
                                    </div>
                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn" lay-filter="customerContactsListSubSearchLog" lay-submit>查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="customerContactsListSearchReset" lay-submit>重置</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <a id="confirmChoose" class="layui-btn icon-btn">确认选择</a>
                        </div>
                    </div>
                </div>
            </form>
            <table class="layui-table" id="customerContactsListTable" lay-filter="customerContactsListTable"></table>
        </div>
    </div>
</script>

<!-- 表格头部操作 -->
<script type="text/html" id="orderTableToolbar">
    <a class="layui-btn" lay-event="add">添加商品</a>
</script>

<script type="text/html" id="orderFormTableBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!--在库的所有物料-->
<script type="text/html" id="productsInStockForm">
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body">
                <!-- 头部操作栏 -->
                <div class="layui-form toolbar">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label w-auto">sku编码：</label>
                            <div class="layui-input-inline mr0" style="width: 240px;">
                                <input name="skuCode" class="layui-input" type="text" placeholder="sku编码"/>
                            </div>
                        </div>
                        <div class="layui-inline" id="warehouseDiv">
                            <label class="layui-form-label w-auto">仓库：</label>
                            <div class="layui-input-inline mr0" style="width: 240px;">
                                <select name="warehouseId"></select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button class="layui-btn icon-btn" lay-filter="productsInStockFormSubSearchLog"
                                    lay-submit style="padding: 0 24px;">
                                搜索
                            </button>
                            <button id="productsInStockFormClose" class="layui-btn icon-btn">确认选择</button>
                        </div>
                    </div>
                </div>
                <!-- 表格 -->
                <table class="layui-table" id="productsInStockFormTable"
                       lay-filter="productsInStockFormTable"></table>
            </div>
        </div>
    </div>
</script>


<!-- 销售订单详情 -->
<script type="text/html" id="orderDetailsForm">
    <form lay-filter="orderDetailsForm" class="layui-form model-form"
          style="padding: 5px 30px 0 30px;height: calc(100% - 5px);overflow: hidden;">
        <div class="open-details-box"
             style="height: calc(100% - 100px); padding-top: 20px;overflow: auto;margin-bottom: 20px">
            <input name="id" type="hidden"/>

            <div class="layui-form-item">
                <div class="open-details-title" style="margin-top: 20px">销售订单详情</div>
                <table class="layui-table" id="orderDetailsFormTable" lay-filter="orderDetailsFormTable"></table>
            </div>
            <div class="layui-form-item">
                <div class="open-details-title" style="margin-top: 20px">销售订单物料列表</div>
                <table class="layui-table" id="orderDetailsTableList" lay-filter="orderDetailsTableList"></table>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="orderDetailsFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>


<!--确认弹窗-->
<script type="text/html" id="distributionDemandAffirm">
    <div class="lay-dialog-title">
        <span>订单基本信息</span>
    </div>
    <form lay-filter="distributionDemandAffirm" class="layui-form model-form">
        <input type="hidden" name="id">
        <div class="layui-card-body" style="padding: 10px 20px">
            <!-- 表格 -->
            <!--<table class="layui-table" id="orderAffirmTopTable" lay-filter="orderDetailTable"></table>-->
            <table class="layui-table">
                <thead>
                <tr>
                    <th>销售订单编号</th>
                    <th>销售方式</th>
                    <th>客户名称</th>
                    <th>收货地址</th>
                    <th>所属经销商</th>
                    <th>业务员</th>
                    <th>sku数</th>
                    <th>仓库源</th>
                    <th>选择仓库</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td>
                        <div id="code"></div>
                    </td>
                    <td>
                        <div id="modeDesc"></div>
                    </td>
                    <td>
                        <div id="customerName"></div>
                    </td>
                    <td>
                        <div>姓名：<span id="contactsName"></span></div>
                        <div>电话：<span id="phone"></span></div>
                        <div>地址：<span id="address"></span></div>
                    </td>
                    <td>
                        <div id="enterpriseName"></div>
                    </td>
                    <td>
                        <div id="operatorName"></div>
                    </td>
                    <td>
                        <div id="skuNum"></div>
                    </td>
                    <td style="width: 180px">
                        <!--<select name="warehouseSource" lay-filter="warehouseSource">
                            <option value="0">进销存</option>
                            <option value="1">云端云仓</option>
                        </select>-->
                        <div id="warehouseSourceDesc"></div>
                    </td>
                    <td style="width: 180px">
                        <div>
                            <input name="warehouseId" type="hidden" lay-verify="warehouse" />
                            <input name="warehouseName" class="layui-input warehouseName" style="cursor: pointer;" readonly placeholder="选择发货仓库" />
                        </div>
                    </td>
                </tr>
                </tbody>
            </table>

        </div>
        <div class="lay-dialog-title">
            <span>订单物料信息</span>
        </div>
        <div class="layui-card-body" style="padding: 0 20px" id="confirm">
            <!-- 表格 -->
            <table class="layui-table" id="orderAffirmBottomTable" lay-filter="orderDetailTable"></table>
        </div>
        <input type="hidden" name="warehouseName" value="">
        <div id="serviceProviders" style="display: none;">
            <div class="layui-form-item">
                <label class="layui-form-label w-100">仓库服务商</label>
                <div class="layui-input-block" style="margin-left: 130px;width: 500px;">
                    <input id="warehouseCompany" type="text" class="layui-input" readonly style="border: 0px"/>
                </div>
            </div>
            <div class="layui-form-item" >
                <label class="layui-form-label w-100">服务商地址</label>
                <div class="layui-input-block" style="margin-left: 130px;width: 500px;">
                    <input id="warehouseAddressCompany" type="text" class="layui-input" readonly style="border: 0px"/>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label w-100">订单描述</label>
            <div class="layui-input-block" style="margin-left: 130px;width: 300px;">
                <input name="orderDetail" placeholder="请输入描述" type="text" class="layui-input"/>
            </div>
        </div>
        <div class="layui-form-item text-right" style="margin-right: 20px">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="distributionDemandAffirmSubmit" lay-submit>确认</button>
        </div>
    </form>
</script>

<!--选择仓库输入框-->
<script type="text/html" id="warehouseName">
    <div>
        <input name="warehouseId" type="hidden" lay-verify="warehouse" />
        <input name="warehouseName" class="layui-input warehouseName" style="cursor: pointer;" readonly placeholder="选择发货仓库" />
    </div>
</script>

<!--选择仓库弹窗-->
<script type="text/html" id="warehouseList">
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-body">
                <!-- 头部操作栏 -->
                <div class="layui-form toolbar">
                    <div class="layui-form-item">
                        <div class="layui-inline" id="enterpriseCode" style="display: none;">
                            <div class="layui-input-inline">
                                <select id="warehouseList-enterpriseCode" lay-filter="enterpriseCode" lay-search>
                                    <option value="">请选择企业</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <div class="layui-input-inline">
                                <input id="warehouseList-name" class="layui-input" type="text" placeholder="请输入名称"/>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <div class="layui-input-inline">
                                <input id="warehouseList-code" class="layui-input" type="text" placeholder="请输入编码"/>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button class="layui-btn icon-btn" id="warehouseList-btn-search" style="padding: 0 24px;">
                                搜索
                            </button>
                            <button id="warehouseList-btn-choose" class="layui-btn icon-btn">确认选择</button>
                        </div>
                    </div>
                </div>
                <!-- 表格 -->
                <table class="layui-table" id="warehouseListTable" lay-filter="warehouseListTable"></table>
            </div>
        </div>
    </div>
</script>

<!--计划配货数输入框-->
<script type="text/html" id="quantity">
    {{# if(d.stayDistributionNum != 0 && d.stock != 0){ }}
    <input name="quantity" class="layui-input" type="text" placeholder="请输入" lay-verify="integer|compare" />
    {{# }else{ }}
    -
    {{# } }}
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin','laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;
        var laydate = layui.laydate;
        var code = layui.config.getUser().cpmCode;
        // 渲染表格
        var insTb = table.render({
            elem: '#orderTable',
            url: config.base + 'enterprise/purchase/admin/cabinetPurchaseOrder/list',
            //where:{type:"cabinet",enterpriseCode:code,mode:"sell"},
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers', title: '序号'}
                , {field: 'code', sort: true, title: '采购订单编号'}
                , {field: 'modeDesc', sort: false, title: '业务类型'}
                , {field: 'quantity', sort: false, title: '柜体台数'}
                , {field: 'amount', sort: true, title: '订单总金额'}
                , {field: 'operatorName', sort: false, title: '采购人员'}
                , {field: 'statusDesc', sort: false, title: '状态'}
                , {field: 'distributionStatusDesc', sort: false, title: '备货状态'}
                , {field: 'createTime', sort: false, title: '提交时间'}
                , {align: 'left', toolbar: '#orderTableBar', title: '操作', width: 150}
            ]],
            done: function (res, curr, count) {
            }
        });

        // 工具条点击事件
        table.on('tool(orderTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                showDetailsModel(data, 'edit');
            } else if (obj.event === 'confirm') { // 确定
                doConfirm(obj);
            } else if (obj.event === 'details') { // 详情
                showDetailsModel(data, 'details');
            } else if (obj.event === 'audit') { //受理配货
                showAffirmModel(data);
            }
        });

        //监听排序
        table.on('sort(orderTable)', function (obj) {
            table.reload('orderTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        // 添加按钮点击事件
        $('#orderBtnAdd').click(function () {
            showEditModel();
        });

        let orderFormTableData = []; //添加订单table数据

        // 显示添加订单弹窗
        function showEditModel(data) {
            orderFormTableData = [];
            admin.open({
                type: 1,
                area: ["85%", "85%"],
                offset: '65px',
                title: '添加订单',
                content: $('#orderForm').html(),
                success: function () {
                    var warehouseSource = "";
                    form.render('select');

                    form.verify({
                        decimal: [/^[0-9]*(\.[0-9]{1,2})?$/, '格式错误'],
                        taxRate: function (data, item) {
                            var taxRate = Number(data); // 税率
                            if (taxRate < 0 || taxRate > 100) {
                                return '请确认税率范围为(0~100)';
                            }
                        },
                        quantity: function (data, item) {
                            var quantity = Number(data); // 税率
                            if (quantity <= 0) {
                                return '请确认数量大于0';
                            }
                        }
                    });

                    if (data) {
                        var option = $("form select[name='status']").find("option");
                        layui.each(option, function (index, item) {
                            if (data.status == item.text) {
                                data.status = item.value;
                            }
                        });
                    }
                    //销售方式下拉事件
                    form.on('select(mode)', function (data) {
                        if($(data.elem).find("option:selected").attr("value")!='sell'){
                            $('#leaseLength').show();
                        }else{
                            $('#leaseLength').hide();
                            $('#leaseLength').val('');
                        }
                    });
                    // 销售
                    admin.reqSync('user/admin/user/list', {limit:99999}, function (res) {
                        if (res.code == 200) {
                            loadSelectHtml(res.data, "销售员", "operatorName", 5, 'orderForm');
                        }
                    }, 'GET');

                    // 合同
                   /* admin.reqSync('platform/sell/admin/customerContract/list', {limit:99999}, function (res) {
                        if (res.code == 200) {
                            loadSelectHtml(res.data, "合同", "contractId", 3, 'orderForm');
                        }
                    }, 'GET');

                    // 选择仓库源
                    form.on('select(getWarehouseSource)', function (d) {
                        if(warehouseSource != d.value){
                            // 清空商品数据
                            orderFormTableData = [];
                            table.reload('orderFormTable', {data: orderFormTableData});
                        }
                        warehouseSource = d.value;
                    })*/

                    laydate.render({
                        elem: '#arrivalTime' //指定元素
                        ,type: 'datetime'
                        ,value: new Date()
                        ,isInitValue: true
                        ,min: 0
                    });
                    let orderFormTb = table.render({
                        elem: '#orderFormTable',
                        data: orderFormTableData,
                        page: false,
                        cellMinWidth: 100,
                        height: 600,
                        toolbar: '#orderTableToolbar',
                        limit: Number.MAX_VALUE,
                        defaultToolbar: [],
                        cols: [[
                            {type: 'numbers', title: '序号'}
                            , {field: 'skuName', title: '物料名称'}
                            , {field: 'skuCode', title: '物料编码', templet: d => {
                                    if (d.combineCode){
                                        var str = d.combineCode.replace(code+"_","");
                                        return str;
                                    }
                                    return d.skuCode;
                                }
                            }
                            , {field: 'skuSpecValueNames', title: '规格码'}
                            , {field: 'productTypeName', title: '类型'}
                            , {field: 'brandName', title: '品牌'}
                            , {field: 'costPrice', title: '成本价'}
                            , {
                                field: 'activityPrice',
                                title: '销售价',
                                // templet: d => '<input type="text" name="discountPrice" class="layui-input" lay-verify="number" value="' + d.discountPrice + '" onkeyup="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">'
                            }
                            , {
                                field: 'tax', title: '是否含税', templet: d => {
                                    let trueValue = '', falseValue = '';
                                    if (d.tax+"" == 'true') {
                                        trueValue = ' selected="" ';
                                        falseValue = '';
                                    } else {
                                        trueValue = '';
                                        falseValue = ' selected="" ';
                                    }
                                    let selectHTML = '<select name="tax" lay-filter="tax">';
                                    selectHTML += '<option value="true" ' + trueValue + '>含税</option>';
                                    selectHTML += '<option value="false" ' + falseValue + '>不含税</option>';
                                    selectHTML += '</select>';
                                    return selectHTML
                                }
                            }
                            , {
                                field: 'taxRate',
                                title: '税率(%)',
                                templet: d => '<input type="text" name="taxRate" lay-verify="required|decimal|taxRate" class="layui-input" value="' + d.taxRate + '">'
                            }
                            , {
                                field: 'quantity',
                                title: '数量',
                                templet: d => '<input type="text" name="quantity" class="layui-input" lay-verify="number|quantity" value="' + d.quantity + '" onkeyup="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">'
                            }
                            , {field: 'total', title: '总价'}
                            , {align: 'center', toolbar: '#orderFormTableBar', title: '操作'}
                        ]],
                        done: function (res, curr, count) {
                            let formAmount = 0;
                            res.data.forEach(item => formAmount += (item.total * 1));
                            $('form[lay-filter="orderForm"] input[name="amount"]').val(formAmount);
                        }
                    });
                    let proType='cabinet';
                    form.on('select(type)', function (data) {
                        proType=data.value;
                    });
                    // table头部操作
                    table.on('toolbar(orderFormTable)', function (obj) {
                        let data = obj.data;
                        if (obj.event === 'add') { //添加商品
                            productsInStockModel();
                        }
                    });

                    // 工具条点击事件
                    table.on('tool(orderFormTable)', function (obj) {
                        let data = obj.data;
                        if (obj.event === 'del') { // 删除
                            orderFormTableData.splice(obj.tr.index(), 1);
                            table.reload('orderFormTable', {data: orderFormTableData});
                        }
                    });

                    $("body").delegate("[lay-id='orderFormTable'] input[name='taxRate']", "change", function () {
                        if (orderFormTableData[$(this).parents('tr').index()]) {
                            var taxRate = $(this).val().trim();
                            var tax = orderFormTableData[$(this).parents('tr').index()].tax;
                            var activityPrice = orderFormTableData[$(this).parents('tr').index()].activityPrice;
                            var quantity = orderFormTableData[$(this).parents('tr').index()].quantity;
                            orderFormTableData[$(this).parents('tr').index()].taxRate = taxRate;
                            orderFormTableData[$(this).parents('tr').index()].total = calculationTotal(activityPrice, quantity, tax, taxRate);
                            orderFormTb.reload({data: orderFormTableData});
                        }
                    });

                    $("body").delegate("[lay-id='orderFormTable'] input[name='quantity']", "change", function () {
                        if (orderFormTableData[$(this).parents('tr').index()]) {
                            var quantity = $(this).val().trim();
                            var activityPrice = orderFormTableData[$(this).parents('tr').index()].activityPrice;
                            var tax = orderFormTableData[$(this).parents('tr').index()].tax;
                            var taxRate = orderFormTableData[$(this).parents('tr').index()].taxRate;
                            orderFormTableData[$(this).parents('tr').index()].quantity = quantity;
                            orderFormTableData[$(this).parents('tr').index()].total = calculationTotal(activityPrice, quantity, tax, taxRate);
                            orderFormTb.reload({data: orderFormTableData});
                        }
                    });

                    form.on("select", function (data) {
                        if ($(data.elem).attr('name') == 'tax') {
                            var tax = data.value;
                            var taxRate = orderFormTableData[$(data.elem).parents('tr').index()].taxRate;
                            var activityPrice = orderFormTableData[$(data.elem).parents('tr').index()].activityPrice;
                            var quantity = orderFormTableData[$(data.elem).parents('tr').index()].quantity;
                            orderFormTableData[$(data.elem).parents('tr').index()].tax = tax;
                            orderFormTableData[$(data.elem).parents('tr').index()].total = calculationTotal(activityPrice, quantity, tax, taxRate);
                            orderFormTb.reload({data: orderFormTableData});
                        }
                    });

                    // 计算总价
                    function calculationTotal(activityPrice, quantity, tax, taxRate){
                        var total = 0;
                        if(tax+"" == 'false'){ // 不含税，计算不含税总价 = 销售价 * (100 + 税率) / 100
                            total = activityPrice * quantity * (100 + Number(taxRate)) / 100;
                        }else{
                            total = activityPrice * quantity;
                        }
                        return total;
                    }

                    form.val('orderForm', data);
                    // 表单提交事件
                    form.on('submit(orderFormSubmit)', function (d) {
                        let objData = {};
                        if (orderFormTableData.length == 0) {
                            layer.msg('请添加商品', {icon: 5});
                            return false;
                        }
                        objData.proList = orderFormTableData;
                        objData.customerCode=d.field.customerCode;
                        objData.address = d.field.address;
                        /*objData.customerContactsId = d.field.customerContactsId;*/
                        objData.contactsName = d.field.contactsName;
                        objData.phone = d.field.phone;
                        objData.amount = d.field.amount;
                        objData.remark = d.field.remark;
                        objData.mode = d.field.mode;
                        objData.type =d.field.type;
                        objData.startTime =d.field.startTime;
                        objData.contractId =d.field.contractId;
                        objData.operatorName =d.field.operatorName;
                        objData.quantity=orderFormTableData.length;
                        //objData.sourceType="platform";
                        /*if(d.field.leaseLength){
                            objData.leaseLength=d.field.leaseLength;
                        }*/
                        //objData.enterpriseCode=code;
                        //objData.warehouseSource = d.field.warehouseSource;

                        objData.arrivalTime=d.field.arrivalTime;
                        layer.load(2);
                        admin.req(data ? 'platform/sell/admin/order/update' : 'enterprise/sell/admin/order/addCabinetPurchaseOrder', JSON.stringify(objData), function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('orderTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST', true, 'application/json; charset=utf-8');
                        return false;
                    });
                }
            });
        }

        //所有商品
        function productsInStockModel() {
            let productsInStockPop = admin.open({
                type: 1,
                area: ["80%", "80%"],
                offset: '75px',
                title: '在库所有物料',
                content: $('#productsInStockForm').html(),
                success: function () {
                    form.render("select");
                    let productsInStockFormTb;
                        productsInStockFormTb = table.render({
                            elem: '#productsInStockFormTable',
                            url: config.base + 'enterprise/product/admin/productDetail/getChannelProductDetailList',
                            //where:{type:"cabinet",enterpriseCode:code,mode:"sell"},
                            page: true,
                            cellMinWidth: 100,
                            cols: [[
                                {type: 'checkbox', fixed: 'left'}
                                , {field: 'skuName', title: 'SKU物料名称'}
                                , {field: 'skuCode', title: 'SKU编码'}
                                , {field: 'skuSpecValueNames', title: 'SKU规格'}
                                , {field: 'productTypeName', title: '类型'}
                                , {field: 'brandName', title: '品牌'}
                                , {field: 'warehouseName', title: '仓库'}
                                , {field: 'enterpriseName', title: '供货商'}
                                , {field: 'costPrice', title: '成本价'}
                                , {field: 'activityPrice', title: '销售价'}
                                //, {align: 'left', toolbar: '#orderTableBar', title: '操作', width: 150}
                            ]],
                            parseData: function (res) {
                                    let resData = [];
                                    resData = res.data.filter(item => orderFormTableData.every(item1 => item1.skuCode !== item.skuCode));
                                    res.data = resData;
                                    return res;
                            },
                            done: function (res, curr, count) {
                            }
                        });


                    // 搜索
                    form.on('submit(productsInStockFormSubSearchLog)', function (data) {
                        productsInStockFormTb.reload({where: data.field, page: {curr: 1}}, 'data');
                    });

                    function getLowestPrice(skuCode){
                        let price='';
                        admin.reqSync('platform/sell/admin/order/getLowestPrice?skuCode='+skuCode,{},res=>{
                            if (res.code==200){
                                price=res.data.lowPrice;
                            }
                        },'get');
                        return price;
                    }

                    $('#productsInStockFormClose').click(function () {
                        let checkRows = table.checkStatus('productsInStockFormTable');
                        if (checkRows.data.length == 0) {
                            layer.msg('请选择要添加的商品', {icon: 5});
                        } else {
                                checkRows.data.forEach(item => {
                                    /*if (warehouseSource == "smartCabinet"){
                                        item.skuCode = item.combineCode;
                                    }*/
                                    item.taxRate = 0;
                                    item.number = 1;
                                    item.tax = false;
                                    // item.total = 0;
                                    //item.proId = item.id;
                                    //item.id = '';
                                    item.lowestPrice = item.costPrice;
                                    item.discountPrice = item.activityPrice;
                                    item.proTypeId=item.productTypeId;
                                    item.brandId=item.brandId;
                                    item.quantity=1;
                                    item.total = item.activityPrice * item.quantity;
                                });

                                orderFormTableData = [...orderFormTableData, ...checkRows.data];
                                table.reload('orderFormTable', {data: orderFormTableData});
                             /*else if (_type === 'edit') {
                                checkRows.data.forEach(item => {
                                    if (warehouseSource == "smartCabinet"){
                                        item.skuCode = item.combineCode;
                                    }
                                    item.taxRate = 0;
                                    item.number = 1;
                                    item.tax = false;
                                    // item.total = 0;
                                    //item.proId = item.id;
                                    item.id = '';
                                    item.lowestPrice = item.costPrice;
                                    item.discountPrice = item.activityPrice;
                                    item.proTypeId=item.productTypeId;
                                    item.brandId=item.brandId;
                                    item.quantity=1;
                                    item.total = item.activityPrice * item.quantity;
                                });
                                orderDetailsTableListTbData = [...orderDetailsTableListTbData, ...checkRows.data];
                                table.reload('orderDetailsTableList', {data: orderDetailsTableListTbData});
                            }*/

                            layer.close(productsInStockPop);
                        }
                    })
                }
            })
        }

        // 显示订单详情、修改弹窗
        let orderDetailsTableListTbData = [];

        function showDetailsModel(data, _type) {
            orderDetailsTableListTbData = [];
            admin.open({
                type: 1,
                area: ["85%", "85%"],
                offset: '65px',
                title: _type == 'edit' ? '修改订单' : '订单详情',
                content: $('#orderDetailsForm').html(),
                success: function () {
                    form.verify({
                        decimal: [/^[0-9]*(\.[0-9]{1,2})?$/, '格式错误'],
                        taxRate: function (data, item) {
                            var taxRate = Number(data); // 税率
                            if (taxRate < 0 || taxRate > 100) {
                                return '请确认税率范围为(0~100)';
                            }
                        },
                        quantity: function (data, item) {
                            var quantity = Number(data); // 税率
                            if (quantity <= 0) {
                                return '请确认数量大于0';
                            }
                        }
                    });

                    orderDetailsTableListTbData = [];
                    admin.reqSync('enterprise/sell/admin/order/getCabinetPurchaseOrderProVOList?orderId=' + data.id, {}, res => {
                        if (res.code === 200) {
                            orderDetailsTableListTbData = res.data;
                        }
                    }, 'get');

                    if (_type == 'edit') {
                        $('button[lay-filter="orderDetailsFormSubmit"]').show();
                    } else {
                        $('button[lay-filter="orderDetailsFormSubmit"]').hide();
                    }

                    var cols = [
                        {field: 'code', title: '销售订单编号'}
                        , {field: 'code', sort: true, title: '采购订单编号'}
                        , {field: 'modeDesc', sort: false, title: '业务类型'}
                        , {field: 'quantity', sort: false, title: '柜体台数'}
                        , {field: 'amount', sort: true, title: '订单总金额'}
                        , {field: 'operatorName', sort: false, title: '采购人员'}
                        , {field: 'statusDesc', sort: false, title: '状态'}
                        , {field: 'distributionStatusDesc', sort: false, title: '备货状态'}
                        , {field: 'createTime', sort: false, title: '提交时间'}
                    ];
                    /*if(data.mode != 'sell'){
                        cols = [
                            {field: 'code', title: '销售订单编号'}
                            , {field: 'typeDesc', title: '订单类型'}
                            , {field: 'modeDesc', title: '销售方式'}
                            , {field: 'enterpriseName', title: '渠道名称'}
                            , {field: 'customerName', title: '客户名称'}
                            , {field: 'contactsName', title: '客户联系人'}
                            , {field: 'quantity', title: '物料数量'}
                            , {field: 'amount', title: '订单货值'}
                            , {field: 'leaseLengthDesc', title: '时长'}
                            , {field: 'operatorName', title: '销售人员'}
                            , {field: 'creatorName', title: '创建人'}
                            , {field: 'statusDesc', title: '状态'}
                            , {field: 'createTime', title: '创建时间'}
                        ];
                    }*/
                    let orderDetailsFormTb = table.render({
                        elem: '#orderDetailsFormTable',
                        data: [data],
                        page: false,
                        cellMinWidth: 100,
                        cols: [cols],
                    });

                    let orderDetailsTableListTb = table.render({
                        elem: '#orderDetailsTableList',
                        data: orderDetailsTableListTbData,
                        toolbar: _type == 'edit' ? '#orderTableToolbar' : '',
                        defaultToolbar: [],
                        height: 600,
                        page: false,
                        limit: Number.MAX_VALUE,
                        cellMinWidth: 100,
                        cols: [[
                            {type: 'numbers', title: '序号'}
                            , {field: 'skuName', title: 'SKU物料名称'}
                            , {field: 'skuCode', title: 'SKU编码'}
                            , {field: 'skuSpecValueNames', title: 'SKU规格'}
                            , {field: 'productTypeName', title: '类型'}
                            , {field: 'brandName', title: '品牌'}
                            , {field: 'lowestPrice', title: '成本价'}
                            , {
                                field: 'discountPrice',
                                title: '销售价',
                                /*templet: d => {
                                    if (_type == 'edit') {
                                        return '<input type="text" name="discountPrice" class="layui-input" lay-verify="number" value="' + d.discountPrice + '" onkeyup="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">'
                                    } else {
                                        return d.discountPrice
                                    }
                                }*/
                            }
                            , {
                                field: 'tax', title: '是否含税', templet: d => {
                                    if (_type == 'edit') {
                                        let trueValue = '', falseValue = '';
                                        if (d.tax+"" == 'true') {
                                            trueValue = ' selected="" ';
                                            falseValue = '';
                                        } else {
                                            trueValue = '  ';
                                            falseValue = ' selected="" ';
                                        }
                                        let selectHTML = '<select name="tax" lay-filter="tax">';
                                        selectHTML += '<option value="true" ' + trueValue + '>含税</option>';
                                        selectHTML += '<option value="false" ' + falseValue + '>不含税</option>';
                                        selectHTML += '</select>';
                                        return selectHTML
                                    } else {
                                        return d.tax ? '含税' : '<span style="color: red">不含税</span>'
                                    }

                                }
                            }
                            , {
                                field: 'taxRate',
                                title: '税率(%)',
                                templet: d => {
                                    if (_type == 'edit') {
                                        return '<input type="text" name="taxRate" lay-verify="required|decimal|taxRate" class="layui-input" value="' + d.taxRate + '">'
                                    } else {
                                        return d.taxRate
                                    }
                                }
                            }
                            , {
                                field: 'quantity',
                                title: '数量',
                                templet: d => {
                                    if (_type == 'edit') {
                                        return '<input type="text" name="quantity" class="layui-input" lay-verify="number|quantity" value="' + d.quantity + '" onkeyup="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">'
                                    } else {
                                        return d.quantity
                                    }
                                }
                            }
                            , {field: 'total', title: '总价'}
                            , _type == 'edit' ? {align: 'center', toolbar: '#orderFormTableBar', title: '操作'} : ''
                        ]],
                    });
                    let proType=data.type;
                    // table头部操作
                    table.on('toolbar(orderDetailsTableList)', function (obj) {
                        let data = obj.data;
                        if (obj.event === 'add') { //添加商品
                            productsInStockModel();

                        }
                    });

                    // 工具条点击事件
                    table.on('tool(orderDetailsTableList)', function (obj) {
                        let data = obj.data;
                        if (obj.event === 'del') { // 删除
                            orderDetailsTableListTbData.splice(obj.tr.index(), 1);
                            table.reload('orderDetailsTableList', {data: orderDetailsTableListTbData});
                        }
                    });

                    $("body").delegate("[lay-id='orderDetailsTableList'] input[name='taxRate']", "change", function () {
                        if (orderDetailsTableListTbData[$(this).parents('tr').index()]) {
                            var taxRate = $(this).val().trim();
                            var tax = orderDetailsTableListTbData[$(this).parents('tr').index()].tax;
                            var activityPrice = orderDetailsTableListTbData[$(this).parents('tr').index()].discountPrice;
                            var quantity = orderDetailsTableListTbData[$(this).parents('tr').index()].quantity;
                            orderDetailsTableListTbData[$(this).parents('tr').index()].taxRate = taxRate;
                            orderDetailsTableListTbData[$(this).parents('tr').index()].total = calculationTotal(activityPrice, quantity, tax, taxRate);
                            orderDetailsTableListTb.reload({data: orderDetailsTableListTbData});
                        }
                    });

                    $("body").delegate("[lay-id='orderDetailsTableList'] input[name='quantity']", "change", function () {
                        if (orderDetailsTableListTbData[$(this).parents('tr').index()]) {
                            var quantity = $(this).val().trim();
                            var activityPrice = orderDetailsTableListTbData[$(this).parents('tr').index()].discountPrice;
                            var tax = orderDetailsTableListTbData[$(this).parents('tr').index()].tax;
                            var taxRate = orderDetailsTableListTbData[$(this).parents('tr').index()].taxRate;
                            orderDetailsTableListTbData[$(this).parents('tr').index()].quantity = quantity;
                            orderDetailsTableListTbData[$(this).parents('tr').index()].total = calculationTotal(activityPrice, quantity, tax, taxRate);
                            orderDetailsTableListTb.reload({data: orderDetailsTableListTbData});
                        }
                    });

                    form.on("select", function (data) {
                        if ($(data.elem).attr('name') == 'tax') {
                            var tax = data.value;
                            var taxRate = orderDetailsTableListTbData[$(data.elem).parents('tr').index()].taxRate;
                            var activityPrice = orderDetailsTableListTbData[$(data.elem).parents('tr').index()].discountPrice;
                            var quantity = orderDetailsTableListTbData[$(data.elem).parents('tr').index()].quantity;
                            orderDetailsTableListTbData[$(data.elem).parents('tr').index()].tax = tax;
                            orderDetailsTableListTbData[$(data.elem).parents('tr').index()].total = calculationTotal(activityPrice, quantity, tax, taxRate);
                            orderDetailsTableListTb.reload({data: orderDetailsTableListTbData});
                        }
                    });

                    // 计算总价
                    function calculationTotal(activityPrice, quantity, tax, taxRate){
                        var total = 0;
                        if(tax+"" == 'false'){ // 不含税，计算不含税总价 = 销售价 * (100 + 税率) / 100
                            total = activityPrice * quantity * (100 + Number(taxRate)) / 100;
                        }else{
                            total = activityPrice * quantity;
                        }
                        return total;
                    }

                    form.on('submit(orderDetailsFormSubmit)', function (d) {
                        let objData = {};
                        if (orderDetailsTableListTbData.length == 0) {
                            layer.msg('请添加商品', {icon: 5});
                            return false;
                        }
                        objData = data;
                        objData.proList = orderDetailsTableListTbData;

                        layer.load(2);
                        admin.req('enterprise/sell/admin/order/updateCabinetPurchaseOrder', JSON.stringify(objData), function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('orderTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'PUT', true, 'application/json; charset=utf-8');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('platform/sell/admin/order/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }

        //确认
        function doConfirm(obj) {
            layer.confirm('确认收货吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                let objData = {};
                objData.id =obj.data.id;
                objData.status='affirm';
                admin.req('enterprise/sell/admin/order/updateCabinetPurchaseOrder', JSON.stringify(objData), function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        insTb.reload()
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'PUT',true,'application/json; charset=utf-8');
            });
        }

        // 显示确认弹窗
        function showAffirmModel(data) {
            let affirmData = [];
            affirmData.push(data);
            admin.open({
                type: 1,
                area: ['80%', '840px'],
                offset: '65px',
                title: '受理配货',
                content: $('#distributionDemandAffirm').html(),
                success: function () {
                    form.verify({
                        integer: [/^([1-9]\d*|[ \t]*)$/, '格式错误'],
                        warehouse: function (data, item) {
                            if(data == ""){
                                return '请选择发货仓库';
                            }
                        },
                        compare: function (data, item) {
                            var stock = Number($(item).parent().parent().prev().find("div").text()); // 仓库库存
                            var stayDistributionQuantity = Number($(item).parent().parent().prev().prev().prev().find("div").text()); // 待配货数
                            if(stock > stayDistributionQuantity){
                                if (stayDistributionQuantity < Number(data)) {
                                    return '计划配货数不能大于待配货数！';
                                }
                            }else{
                                if (stock < Number(data)) {
                                    return '计划配货数不能大于仓库库存！';
                                }
                            }
                        }
                    });

                    $("#code").text(data.code);
                    $("#modeDesc").text(data.modeDesc);
                    $("#customerName").text(data.customerName);
                    $("#contactsName").text(data.contactsName);
                    $("#phone").text(data.phone);
                    $("#address").text(data.provinceDesc+data.cityDesc+data.areaDesc+data.address);
                    $("#enterpriseName").text(data.enterpriseName);
                    $("#operatorName").text(data.operatorName);
                    $("#skuNum").text(data.skuNum);
                    //$("#warehouseSourceDesc").text(data.warehouseSourceDesc);

                    var url = config.base + 'supplier/warehouse/admin/warehouse/list';
                    var subUrl = 'supplier/stock/admin/prepareGoodsTask/add';
                    var proCols = [
                        {type: 'numbers'}
                        , {field: 'id', title: 'ID', hide: "true"}
                        , {field: 'skuCode', title: '物料编号', width: 160}
                        , {field: 'productTypeName', title: '物料类型', width: 100}
                        , {field: 'companyName', title: '所属供应商(货主)', width: 160}
                        , {field: 'skuSpecValueNames', title: '规格', width: 100}
                        , {field: 'unitName', title: '单位', width: 80}
                        , {field: 'totalDistributionNum', title: '总配货数', width: 90}
                        , {field: 'stayDistributionNum', title: '待配货数', width: 90}
                        // , {field: 'statusDesc', title: '状态', width: 130}
                        , {field: 'stock', title: '仓库库存', width: 90}
                        , {field: 'quantity', title: '计划配货数', width: 100, templet: "#quantity"}
                        , {field: 'updateTime', title: '变动时间', width: 170, templet: function (d) {
                                return d.createTime ? d.createTime : d.updateTime
                            }}
                    ];
                    var cols = [
                        {type: 'radio'}
                        ,{field: 'enterpriseCode', sort: true, title: '企业编码'}
                        ,{field: 'name', sort: true, title: '名称'}
                        ,{field: 'code', sort: true, title: '编码'}
                        ,{field: 'addr', sort: true, title: '仓货位置'}
                    ]

                    if(data.warehouseSource == 'stock'){ // 进销存
                        $("#serviceProviders").hide();
                        $("#serviceProviders").find("input").val("");
                        url = config.base + 'supplier/warehouse/admin/warehouse/list';
                        subUrl = 'supplier/stock/admin/prepareGoodsTask/add';
                        proCols = [
                            {type: 'numbers'}
                            , {field: 'skuCode', title: '物料编号', width: 160}
                            , {field: 'productTypeName', title: '物料类型', width: 100}
                            , {field: 'companyName', title: '所属供应商(货主)', width: 160}
                            , {field: 'skuSpecValueNames', title: '规格', width: 100}
                            , {field: 'unitName', title: '单位', width: 80}
                            , {field: 'totalDistributionNum', title: '总配货数', width: 90}
                            , {field: 'stayDistributionNum', title: '待配货数', width: 90}
                            // , {field: 'statusDesc', title: '状态', width: 130}
                            , {field: 'stock', title: '仓库库存', width: 90}
                            , {field: 'quantity', title: '计划配货数', width: 100, templet: "#quantity"}
                            , {field: 'updateTime', title: '变动时间', width: 170, templet: function (d) {
                                    return d.createTime ? d.createTime : d.updateTime
                                }}
                        ];
                        cols = [
                            {type: 'radio'}
                            ,{field: 'enterpriseCode', sort: true, title: '企业编码'}
                            ,{field: 'name', sort: true, title: '名称'}
                            ,{field: 'code', sort: true, title: '编码'}
                            ,{field: 'addr', sort: true, title: '仓货位置'}
                        ]
                    }else{
                        $("#serviceProviders").show();
                        $("#serviceProviders").find("input").val("");
                        url = config.base + 'platformCloud/warehouse/admin/warehouse/list';
                        subUrl = 'platformCloud/cloudOutbound/admin/orderDistribution/add';
                        proCols = [
                            {type: 'numbers'}
                            , {field: 'skuCode', title: '物料编号', width: 160}
                            , {field: 'productTypeName', title: '物料类型', width: 100}
                            , {field: 'channelSkuCode', title: '渠道物料编号', width: 140}
                            , {field: 'companyName', title: '所属供应商(货主)', width: 160}
                            , {field: 'skuSpecValueNames', title: '规格', width: 100}
                            , {field: 'unitName', title: '单位', width: 80}
                            , {field: 'totalDistributionNum', title: '总配货数', width: 90}
                            , {field: 'stayDistributionNum', title: '待配货数', width: 90}
                            // , {field: 'statusDesc', title: '状态', width: 130}
                            , {field: 'stock', title: '仓库库存', width: 90}
                            , {field: 'quantity', title: '计划配货数', width: 100, templet: "#quantity"}
                            , {field: 'updateTime', title: '变动时间', width: 170, templet: function (d) {
                                    return d.createTime ? d.createTime : d.updateTime
                                }}
                        ];
                        cols = [
                            {type: 'radio'}
                            ,{field: 'enterpriseName', sort: true, title: '企业名称'}
                            ,{field: 'enterpriseCode', sort: true, title: '企业编码'}
                            ,{field: 'name', sort: true, title: '名称'}
                            ,{field: 'code', sort: true, title: '编码'}
                            ,{field: 'provinceName', sort: true, title: '省'}
                            ,{field: 'cityName', sort: true, title: '市'}
                            ,{field: 'areaName', sort: true, title: '区'}
                            ,{field: 'addr', sort: true, title: '仓货位置'}
                        ]
                    }

                    orderProductInfo(proCols);

                    function orderProductInfo(proCols){
                        table.render({
                            elem: '#orderAffirmBottomTable',
                            url: config.base + 'platform/sell/admin/orderPro/list',
                            where: {orderId: data.id},
                            page: true,
                            cellMinWidth: 100,
                            cols: [proCols]
                        });
                    }

                    $(".warehouseName").click(function () {
                        var $this = $(this);
                        // 获取仓库数据
                        var warehouseList = layer.open({
                            type: 1,
                            title: '仓库列表',
                            area: ['1100px', '700px'],
                            offset: '120px',
                            content: $('#warehouseList').html(),
                            success: function () {
                                form.render("select");

                                if(data.warehouseSource == 'stock'){ // 进销存
                                    $("#enterpriseCode").hide();
                                }else{
                                    $("#enterpriseCode").show();
                                }

                                admin.req('platform/company/admin/company/list', {limit:9999,status:'1',subjectType:'channel'}, function (res) {
                                    if (200 == res.code) {
                                        var optionHtml='<option value="">请选择企业</option>';
                                        for(var k=0;k<res.data.length;k++){
                                            optionHtml+='<option value="'+res.data[k].companyCode+'">'+res.data[k].name+'</option>';
                                        }
                                        $("#warehouseList-enterpriseCode").html(optionHtml);
                                        form.render('select');
                                    } else {
                                        layer.msg('获取企业失败', {icon: 2, time: 1000});
                                    }
                                }, 'GET');

                                // 渲染表格
                                table.render({
                                    elem: '#warehouseListTable',
                                    url: url,
                                    method: 'GET',
                                    page: true,
                                    cols: [cols]
                                });

                                // 搜索按钮点击事件
                                $('#warehouseList-btn-search').click(function () {
                                    var enterpriseCode = $('#warehouseList-enterpriseCode').val();
                                    var name = $('#warehouseList-name').val();
                                    var code = $('#warehouseList-code').val();
                                    table.reload('warehouseListTable', {page: {curr:1}, where: {code: code, name: name, enterpriseCode: enterpriseCode}});
                                });

                                // 确认选择
                                $('#warehouseList-btn-choose').click(function () {
                                    var checkStatus = table.checkStatus('warehouseListTable'); //test即为基础参数id对应的值
                                    var dataS = checkStatus.data;
                                    if (dataS.length == 0) {
                                        layer.msg("请选择仓库", {icon: 2, time: 1000});
                                    }else{
                                        layer.close(warehouseList);
                                        $this.prev().val(dataS[0].id);
                                        $this.val(dataS[0].name);
                                        $("#warehouseCompany").val(dataS[0].enterpriseName);
                                        $("#warehouseAddressCompany").val(dataS[0].companyProvince+dataS[0].companyCity+dataS[0].companyArea+dataS[0].address);

                                        // 筛选订单物料信息
                                        table.reload('orderAffirmBottomTable', {page: {curr:1}, where: {warehouseId: dataS[0].id, warehouseSource: data.warehouseSource}});
                                    }
                                });
                            }
                        })
                    })

                    $("input[name='distributeCode']").val(data.distributeCode);
                    $("input[name='id']").val(data.id);
                    form.render('select');

                    // 表单提交事件
                    form.on('submit(distributionDemandAffirmSubmit)', function (d) {
                        var prepareGoodsTaskDetails = [];
                        $("#confirm").find("tbody tr").each(function (index, item) {
                            var distributionDemandDetail = {};
                            var isAdd = false;
                            $(item).find("td").each(function (tdIndex, tdItem) {
                                if($(tdItem).data("field") == "id"){ // 销售订单明细ID
                                    distributionDemandDetail.orderDetailsId = $(tdItem).find("div").text();
                                }else if($(tdItem).data("field") == "skuCode"){ // skuCode
                                    distributionDemandDetail.skuCode = $(tdItem).find("div").text();
                                }else if($(tdItem).data("field") == "quantity"){ // 计划配货数
                                    distributionDemandDetail.quantity = $(tdItem).find("input").val();
                                    if($(tdItem).find("input").val()){
                                        isAdd = true;
                                    }
                                }
                            })
                            if(isAdd){
                                prepareGoodsTaskDetails.push(distributionDemandDetail);
                            }
                        })
                        if(prepareGoodsTaskDetails.length == 0){
                            layer.msg("请至少输入一条计划配货数", {icon: 2});
                            return false;
                        }
                        d.field.orderId = data.id;
                        d.field.prepareGoodsTaskDetails = prepareGoodsTaskDetails;
                        layer.load(2);
                        admin.req(subUrl, JSON.stringify(d.field), function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('distributionDemandTable');
                                layer.closeAll();
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'POST', true, 'application/json; charset=utf-8');
                        return false;
                    });
                }
            });
        }

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            $(".lay-header").find('select').val("");
            $(".lay-header").find('input').val("");
            var field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            insTb.reload({where: field, page: {curr: 1}}, 'data');
            return false;
        });

        // 渲染下拉框数据
        function loadSelectHtml(data, tips, htmltarget, type, formName) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                if (type === 1) {
                    html += `<option value='${data[i].id}'  customerCode='${data[i].companyCode}' address='${data[i].address}' >${data[i].customerName}</option>`;
                } else if (type === 2) {
                    html += `<option value='${data[i].id}' phone='${data[i].telephone}'>${data[i].name}</option>`;
                } else if (type === 3) {
                    html += `<option value='${data[i].id}'>${data[i].name}</option>`;
                } else if (type === 4) {
                    html += `<option value='${data[i].id}'>${data[i].username}</option>`;
                }else if (type === 5) {
                    html += `<option value='${data[i].username}'>${data[i].username}</option>`;
                }
            }

            $("form[lay-filter='" + formName + "']  select[name='" + htmltarget + "']").html(html);
            form.render('select');
        }

    });
</script>